﻿using System.Threading.Tasks;
using Demo.Api.Data;
using Demo.Api.Models;
using Demo.Api.Services;
using Microsoft.AspNetCore.Mvc;

namespace Demo.Api.Controllers
{
    /// <summary>
    /// 事项
    /// </summary>
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class AffairController : ControllerBase
    {
        private readonly AffairRepository _repository;

        public AffairController(AffairRepository repository)
        {
            _repository = repository;
        }

        /// <summary>
        /// 获取所有的事项
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Gets()
        {
            var result = await _repository.GetsAsync();
            return Ok(result);
        }
        /// <summary>
        /// 获取一个事项
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Get(long id)
        {
            var result = await _repository.GetAsync(id);
            return Ok(result);
        }
        /// <summary>
        /// 添加一个事项
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Add(AffairDto model)
        {
            var temp = model.ToAffairDo();
            temp.Id = IdWorker.NextId();
            if (await _repository.Add(temp))
                return Ok(temp.Id);
            else
            {
                return BadRequest("添加失败");
            }
        }
        /// <summary>
        /// 更新事项信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IActionResult> Update(long id, [FromBody] AffairDto model)
        {
            if (id < 1)
                return BadRequest("Id不正确");
            var temp = await _repository.GetAsync(id);
            temp.Id = id;
            temp.Name = model.Name;
            temp.FlowChartId = model.FlowChartId;
            if (await _repository.Update())
                return Ok();
            else
            {
                return BadRequest("更新失败");
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<IActionResult> Delete(long id)
        {
            var result = await _repository.Delete(id);
            return Ok(result);
        }
    }
}